//
//  ImagePickerExampleViewController.m
//  ImagePickerExample
//

#import "ImagePickerExampleViewController.h"

@implementation ImagePickerExampleViewController

- (void)displaySourceError {
	UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Error"
													  message:@"Image source not available"
													 delegate:nil
											cancelButtonTitle:@"OK"
											otherButtonTitles:nil];
	[myAlert show];
	[myAlert release];
}

- (void)photoLibraryButtonClick:(id)sender {
	//[self presentModalViewController:imagePicker animated:YES];
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
		imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		[self presentModalViewController:imagePicker animated:YES];
	}
	else {
		[self displaySourceError];
	}
}

- (void)cameraLibraryButtonClick:(id)sender {
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
		[self presentModalViewController:imagePicker animated:YES];
	}
	else {
		[self displaySourceError];
	}
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	imagePicker = [[UIImagePickerController alloc] init];
	imagePicker.delegate = self;
	imagePicker.allowsEditing = YES;

	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		NSArray *availableMedia = [UIImagePickerController
								   availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
		imagePicker.mediaTypes = availableMedia;
		NSLog(@"availableMedia: %@", availableMedia);
	}
	
	UIButton *photoLibraryButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[photoLibraryButton setFrame:CGRectMake(100,10,120,34)];
	[photoLibraryButton setTitle:@"Photo Library" forState:UIControlStateNormal];
	[photoLibraryButton addTarget:self action:@selector(photoLibraryButtonClick:)
				 forControlEvents:UIControlEventTouchUpInside];

	[self.view addSubview:photoLibraryButton];
	
	UIButton *cameraButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[cameraButton setFrame:CGRectMake(100,60,120,34)];
	[cameraButton setTitle:@"Camera" forState:UIControlStateNormal];
	[cameraButton addTarget:self action:@selector(cameraLibraryButtonClick:)
		   forControlEvents:UIControlEventTouchUpInside];
	
	[self.view addSubview:cameraButton];
}

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
	
	NSLog(@"info: %@", info);
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)dealloc {
	
	[imagePicker release];
	imagePicker = nil;
	
    [super dealloc];
}

@end
